package zhtt.hibernate.user.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import zhtt.hibernate.user.entity.User;
import zhtt.hibernate.user.repository.UserJapRepository;
import zhtt.hibernate.user.repository.UserRepository;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;
import java.util.List;
import java.util.Optional;

@Service
public class UserService {

    @Autowired
    private UserRepository repository;

    @Autowired
    private UserJapRepository japRepository;

    @PersistenceContext
    private EntityManager entityManager;

    public User getUserById(Long id){
         return  repository.getUserById(id);
//        return japRepository.getOne(id);
    }

    public User save(User user){
        return  repository.save(user);
    }

    public Iterable<User> findAll(){
        return  repository.findAll();
    }

    public Iterable<User> findByName(String name){
        return  null;
    }

    @Transactional()
    public int saves(List<User> userList) {
        StringBuilder sb = new StringBuilder();
        sb.append("INSERT INTO zhtt_user(name) VALUES ");
        for(User user : userList) {
            sb.append("(?),");
        }
        String sql = sb.toString().substring(0, sb.length() - 1);
        Query query = entityManager.createNativeQuery(sql);
        int paramIndex = 1;
        for(User user : userList) {
            query.setParameter(paramIndex++, user.getName());
        }
        return query.executeUpdate();
    }
}
